/**
 * 腾讯云COS上传工具（后端上传方式）
 */
import { apiClient } from './require'

/**
 * 上传结果
 */
interface UploadResult {
  success: boolean
  url: string
  path: string
  message: string
}

/**
 * 下载结果
 */
interface DownloadResult {
  success: boolean
  blob: Blob | null
  message: string
}

/**
 * 后端上传文件到COS
 * 
 * @param file 文件对象
 * @param folder 存储文件夹（默认zongce）
 * @returns 上传结果
 */
export async function uploadToServer(file: File, folder: string = 'zongce'): Promise<UploadResult> {
  try {
    const formData = new FormData()
    formData.append('file', file)
    formData.append('folder', folder)
    
    const response = await apiClient.post('/cos/upload/', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    
    return {
      success: true,
      url: response.data.data.url,
      path: response.data.data.path,
      message: '上传成功'
    }
  } catch (error: any) {
    return {
      success: false,
      url: '',
      path: '',
      message: error.response?.data?.message || '上传失败'
    }
  }
}

/**
 * 通过后端代理下载COS文件（解决跨域问题）
 * 
 * @param fileUrl COS文件URL
 * @returns 下载结果
 */
export async function downloadFromServer(fileUrl: string): Promise<DownloadResult> {
  try {
    const response = await apiClient.get('/cos/proxy-download/', {
      params: { url: fileUrl },
      responseType: 'blob'
    })
    
    return {
      success: true,
      blob: response.data,
      message: '下载成功'
    }
  } catch (error: any) {
    return {
      success: false,
      blob: null,
      message: error.response?.data?.message || '下载失败'
    }
  }
}
